// pages/teacher/teacher.js
import {
  request
} from '../../utils/util.js'
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    page: 1,
    commentList: [],
    has_more: true,
    show_modal: false,
    tab_index: 0, //0：预约，1：简介
    course_index: 0, //选中课程
    course_id: null,
    day_index: 0,
    today: '2019-03-13',
    timeList: [],
    classTypeIndex:0,
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      day_index: options.day_index,
      course_id: options.course_id,
      teacher_id: options.id
    });
    this.getDayList();
    this.getTeacherDetail();
  },

  // 取消预约
  cancelBook(){
    let {time_item,today}=this.data
    // console.log(time_item,today)
    let nowTime =  new Date();
    let thisTime =  new Date(today.replace(/-/g,'/')+' '+time_item.start_time);
    console.log(nowTime,thisTime,(thisTime-nowTime)/60/60/1000)
    let str = Math.abs((thisTime-nowTime)/60/60/1000>8)?'':'开课八小时内取消会扣课时，';
    wx.showModal({
      content: str+'确认要取消当前的预约吗？',
      cancelText:"否",//默认是“取消”
      confirmText:"是",//默认是“确定”
      success:res=> {
        if(res.confirm){
          request({
            url: 'User/cancelBook',
            method: 'POST',
            data: { id:time_item.book_id },
            success: data => {
              wx.showModal({
                title: '温馨提示',
                content: '取消预约成功',
                showCancel: false,
                success:res=>{
                  this.getTeacherDetail()
                },
              })
            }
          })
        }
      },complete:res=>{
        this.setData({show_modal:false})
      }
    })

  },

  //tap切换事件
  changeTap(e) {
    let {index} = e.currentTarget.dataset;
    this.setData({
      tab_index: index
    })

    if (index == 1 && this.data.commentList.length == 0) {
      this.getTeacherCommnet();
    }
  },

  //改选课程
  changeCourse(e) {
    let {index,id} = e.currentTarget.dataset;
    this.setData({
      course_index: index,
      course_id: id
    })
    this.getTimeList();
  },
  
  getClassType(e){
    let {index} = e.currentTarget.dataset;
    this.setData({ classTypeIndex: index })
  },

  // 获取预约时段列表
  getTimeList(){
    let that = this
    let { teacher_id, today, course_id, timeList, day_index } = that.data
    request({
      url: 'Teacher/bookCourseTimeList',
      method: 'GET',
      data: {
        teacher_id,
        date: today,
        course_id,
      },
      success: data => {
        timeList[day_index] = data
        that.setData({
          timeList,
        })
      }
    })
  },

  //获取教师详情&可预约课程
  getTeacherDetail() {
    let that = this;
    let { teacher_id, today, course_id, course_index } = that.data
    request({
      url: 'Teacher/bookTeacherCourse',
      method: 'GET',
      data: {
        teacher_id,
        date: today
      },
      success: data => {
        let courseList = data.teacher_course
        for (let i = 0; i < courseList.length; i++){
          course_index = courseList[i].course_id == course_id ? i : 0
        }
        that.setData({
          teacher: data.teacher,
          courseList,
          course_index
        })
        this.getTimeList()
      }
    })
  },

  //获取7天日期
  getDayList() {
    let dayList = [];
    let timeList = [];
    for (let i = 0; i < 14; i++) {
      let day = this.getDay(i);
      if (i == 0) {
        // day.week = '今';
        this.setData({
          today: day.date
        })
      } else if (i == 1) {
        // day.week = '明'
      }
      dayList.push(day)
      timeList.push([])
    }

    let day_index = this.data.day_index;

    this.setData({
      dayList,
      today: dayList[day_index].date,
      timeList
    })
  },

  //获取日期
  getDay(day) {
    let today = new Date();
    let targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
    today.setTime(targetday_milliseconds); //注意，这行是关键代码
    let tYear = today.getFullYear();
    let tMonth = today.getMonth();
    let tDate = today.getDate();
    tMonth = (tMonth + 1) < 10 ? ("0" + (tMonth + 1)) : (tMonth + 1);
    tDate = tDate < 10 ? ("0" + tDate) : tDate;
    let time = {
      date: tYear + "-" + tMonth + "-" + tDate,
      day: tDate,
      week: "日一二三四五六".charAt(today.getDay()),
      month: tMonth,
    }
    return time;
  },

  //日期改变
  changeDay(e) {
    let { index } = e.currentTarget.dataset
    this.setData({
      day_index: index,
    })
  },

  //日期改变
  dayChange () {
    let { dayList, day_index } = this.data
    this.setData({
      today: dayList[day_index].date,
    })
    this.getTimeList();
  },

  //获取教师评论列表
  getTeacherCommnet() {
    let that = this;
    request({
      url: 'Comment/commentTeacher',
      method: 'GET',
      data: {
        teacher_id: that.data.teacher_id,
        page: that.data.page,
      },
      success: data => {
        let has_more = true;
        if (data.list.length < 10) {
          has_more = false;
        }
        that.setData({
          commentList: [...that.data.commentList, ...data.list],
          commentCount: data.count,
          score: data.score,
          has_more
        })
      }
    })
  },

  //加载更多
  getMore() {
    this.data.page++;
    this.getTeacherCommnet();
  },

  //打开弹框
  openModal(e) {
    let { item } = e.currentTarget.dataset;
    let {today}=this.data;
    let thisTime = new Date(today.replace(/-/g,'/')+' '+item.start_time);
    let nowTime =new Date();
    let state = (thisTime - nowTime)/1000/60/60/24<1;
    if(item.id==0||state&&item.is_book==0&&item.has_candidate==0){
      console.log('不可更改',item.id==0,state,state&&item.is_book==0&&item.has_candidate==0)
    }else{
      if(!item.is_book&&item.book_num>=item.limit){
        item.is_standby = true
      }
      this.setData({
        show_modal: true,
        time_item: item,
        classTypeIndex:item.type==1?0:(item.type==2?1:-1)
      })

    }
  },

  //关闭弹框
  closeModal(e) {
    if (e.currentTarget.dataset.is_close == 1) {
      this.setData({
        show_modal: false
      })
    }
  },

  //确认预约
  confirmBook() {
    let that = this;
    let {
      teacher_id,
      classTypeIndex,
      time_item,
      course_id,
    } = this.data;
    let {id,type}=time_item
    
    if(type==3&&classTypeIndex<0){
      wx.showToast({
        title: '请选择课程形式',
        icon:'none'
      })
    }else{
    request({
      url: 'User/confirmBookTime',
      method: 'POST',
      data: {
        teacher_id: Number(teacher_id),
        time_id: Number(id),
        course_id:Number(course_id),
        type:Number(type!=3?type:(classTypeIndex==0?1:2))
      },
      success: data => {
        this.setData({
          show_modal: false,
          classTypeIndex:-1
        })
        wx.showModal({
          title: '温馨提示',
          content: '预约成功',
          showCancel: false,
          success(res) {
            let messInfo = app.globalData.messInfo
            wx.requestSubscribeMessage({
              tmplIds: [messInfo.course_cancel_sub, messInfo.course_notify_sub],
            })
            that.getTeacherDetail();
          },
        })
      }
    })
  }
  },

  // 左右滑动切换
  swiperChange(e) {
    let index = e.detail.current
    this.setData({
      day_index: index,
    })
    this.dayChange()
  },

  // 候补预约
  standbyBook(){
    let that = this
    let {
      classTypeIndex,
      time_item
    } = that.data;

    let {id,type}=time_item;
    if(type==3&&classTypeIndex<0){
      wx.showToast({
        title: '请选择课程形式',
        icon:'none'
      })
    }else{
      request({
        url: 'User/addCandidate',
        method: 'POST',
        data: {
          time_id: id,
          type:Number(type!=3?type:(classTypeIndex==0?1:2))
        },
        success: data => {
          that.setData({
            show_modal: false,
            classTypeIndex:-1
          })
          wx.showModal({
            content: '已提交候补预约，候补成功将自动预约课程',
            showCancel: false,
            confirmText: '好的',
            success (res) {
              let messInfo = app.globalData.messInfo
              wx.requestSubscribeMessage({
                tmplIds: [messInfo.course_candidate_sub,messInfo.course_cancel_sub, messInfo.course_notify_sub],
              })
              that.getTimeList()
              that.getTeacherDetail();
            }
          })
        }
      })

    }
  },

  // 取消候补
  standbyCancel(){
    let { time_item } = this.data;
    wx.showModal({
      content: '确认要取消当前的候补吗？',
      cancelText:"否",//默认是“取消”
      confirmText:"是",//默认是“确定”
      success:res=> {
        if(res.confirm){
          request({
            url: 'User/cancelCandidate',
            method: 'POST',
            data: {
              time_id: time_item.id,
            },
            success: data => {
              this.setData({
                show_modal: false,
              })
              wx.showModal({
                content: '已取消候补预约',
                showCancel: false,
                confirmText: '好的',
                success:res=> {
                  this.getTimeList()
                }
              })
            }
          })
        }
      },complete:res=>{
        this.setData({show_modal:false})
      }
    })
  }

})